package com.gxa.user.recycling.controller;

import com.gxa.core.recycling.common.ExceptionCode;
import com.gxa.core.recycling.common.JsonResult;
import com.gxa.core.recycling.exception.BusinessException;
import com.gxa.core.recycling.pojo.*;
import com.gxa.core.recycling.util.GetTimeUtil;
import com.gxa.core.recycling.util.RandomUtil;
import com.gxa.core.recycling.util.StringUtil;
import com.gxa.user.recycling.repository.GetImgRepository;
import com.gxa.user.recycling.repository.GoodsRepository;
import com.gxa.user.recycling.repository.ImagesRepository;
import com.gxa.user.recycling.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("/home")
@Transactional(rollbackFor = {Throwable.class})
@Api
public class HomePageController {
    @Autowired
    HomePageService homePageService;
    @Autowired
    UsersService usersService;
    @Autowired

    WasteTypeService wasteTypeService;
    @Autowired
    WastesService wastesService;
    @Autowired
    CommunityManagesService communityManagesService;
    @Autowired
    KeepAddressService keepAddressService;
    @Autowired
    GetCycleService getCycleService;
    @Autowired
    RecycleorderService recycleorderService;
    @Autowired
    GoodsorderService goodsorderService;
    @Autowired
    ImgsService imgsService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    ScoreService scoreService;
    @Autowired
    GetImgRepository getImgRepository;
    //给前端反馈城市列表
    @ApiOperation("给前端反馈城市列表接口")
    @PostMapping("/city")
    public Map selectAll() throws BusinessException {
        List<CommunityManage> communityManages = homePageService.selectAll();
        List list = new ArrayList();
        Set set=new HashSet();
        for (CommunityManage communityManage : communityManages) {
            String provinces = communityManage.getProvinces();
            String[] split = provinces.split("-");
            String substring = null;
            if(split.length>=2){
                substring = split[1];
            }else {
                throw new BusinessException(ExceptionCode.STATE_EXIST);
            }
            set.add(substring);
            list.add(substring);
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(set);
        return jsonResult.getDataMap();
    }
    //给前端反馈炽热兑换商品
    @ApiOperation("给前端反馈炽热兑换商品")
    @PostMapping("/goods")
    public Map selectByHot(){
        List<Map<String, Object>> goodsByHotAndState = goodsService.findGoodsByHotAndState(true, true);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(goodsByHotAndState);
        return jsonResult.getDataMap();
    }
    //主页上面标记的二氧化碳质量
    @ApiOperation("主页上面标记的二氧化碳质量")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "用户id",required = true)})
    @PostMapping("/kg")
    public Map selectAllPoints(@RequestParam("id") Long id){
        User user = usersService.selectById(id);
        Integer allPoints = user.getAllPoints();
        int a=allPoints/100;
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(a);
        return jsonResult.getDataMap();
    }
    //选择地址之后，修改地址
    @ApiOperation("选择地址之后，修改地址的接口")
    @PostMapping("/updateLocation")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "用户id",required = true),
    @ApiImplicitParam(name = "location",value = "详细地址",required = true)})
    public Map updateLocation(@RequestParam("id") Long id,@RequestParam("location") String location){
         usersService.update(id, location);
         JsonResult jsonResult=new JsonResult();
         jsonResult.setCode("200");
         return jsonResult.getDataMap();
    }
    //通过地址查询与获得的地址比较
    @ApiOperation("查询详细地址接口")
    @PostMapping("/selectLocation")
    @ApiImplicitParams({@ApiImplicitParam(name = "location",value = "用户详细地址",required = true)})
    public Map selectLocation(@RequestParam("location") String location) throws BusinessException {
        List<User> list = usersService.selectLocation(location);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(list);
        return jsonResult.getDataMap();
    }
    //废品类型的全查接口
    @ApiOperation("查看废品类型的全查接口")
    @PostMapping("/selectAllWasteType")
    public Map selectAllWasteType(){
        List<WasteType> wasteTypes = wasteTypeService.selectAll();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(wasteTypes);
        return jsonResult.getDataMap();
    }
    @ApiOperation("具体废品种类的全查接口")
    //具体废品种类的全查
    @PostMapping("/selectAllWastes")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "废品类型id",required = true)
    })
    public Map selectAllWastes(@RequestParam("id") Long id){
        List<Waste> wastes = wastesService.selectByType(id);
        for (Waste waste : wastes) {
            Long id1 = waste.getId();
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(wastes);
        return jsonResult.getDataMap();
    }
    //小区的全查，或者模糊查询
    @ApiOperation("小区的全查或者模糊查询")
    @PostMapping("/selectBy")
    @ApiImplicitParams({@ApiImplicitParam(name = "provinces",value = "省市区",required = false)})
    public Map selectBy(String provinces) throws BusinessException {
        List<CommunityManage> communityManages = communityManagesService.selectBy(provinces);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(communityManages);
        return jsonResult.getDataMap();
    }
    //添加服务地址之后，电话号码只能是自己的，要通过id查询得到电话号码
    @ApiOperation("通过id查询得到电话号码接口")
    @PostMapping("/bySelectGetPhone")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "用户id",required = true)})
    public Map bySelectGetPhone(@RequestParam("id") Long id){
        User user = usersService.selectById(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(user);
        return jsonResult.getDataMap();
    }
    //保存服务地址
    @ApiOperation("保存服务地址接口")
    @PostMapping("/keepAddress")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "用户id",required = true),
    @ApiImplicitParam(name = "name",value = "用户姓名",required = false),
            @ApiImplicitParam(name = "phone",value = "用户电话号码",required = false),
    @ApiImplicitParam(name = "aid",value = "小区id",required = true),
    @ApiImplicitParam(name = "daddress",value = "服务地址",required = true)})
    public Map keepAddress(@RequestParam("id")Long id,//用户id
                           String name,
                           String phone,
                           @RequestParam("aid") Long aid,//小区id
                           @RequestParam("daddress")String daddress
                           ){
        Long addaddress = keepAddressService.addaddress(id, name, phone, aid, daddress);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(addaddress);
        return jsonResult.getDataMap();
    }
    @ApiOperation("通过id寻找用户的名字和电话号码，用于进入服务地址页面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true)
    })
    @PostMapping("/bySelectByIdGet")
    public Map bySelectByIdGet(@RequestParam("id")Long id){
        Map map =new HashMap();
        User user = usersService.selectById(id);
        String name = user.getName();
        String phone = user.getPhone();
        map.put("name",name);
        map.put("phone",phone);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    //添加周期上门
    @ApiOperation("添加周期上门接口")
    @PostMapping("/addCycle")
    public Map addCycle(GetCycle getCycle){
        Integer cycle = getCycle.getCycle();
        String weekNum = getCycle.getWeekNum();
        List<GetCycle> getCycles = getCycleService.selectAll();
        Long id=null;
        for (GetCycle getCycle1 : getCycles) {
            Integer cycle1 = getCycle1.getCycle();
            String weekNum1 = getCycle1.getWeekNum();
            if(cycle.equals(cycle1)&&weekNum.equals(weekNum1)){
                id = getCycle1.getId();
            }
        }
        if(id==null) {
            getCycleService.insert(getCycle);
        }
        Long id1 = getCycle.getId();

        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        if(id!=null){
            jsonResult.setData(id);
        }else {
            jsonResult.setData(id1);
        }
        return jsonResult.getDataMap();
    }
    //添加预约订单
    @ApiOperation("添加预约订单接口")
    @PostMapping("/addRecyclingOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true),
            @ApiImplicitParam(name = "title",value = "废品总类型",required =true),
            @ApiImplicitParam(name = "ytime",value = "预约时间",required = true),
            @ApiImplicitParam(name = "did",value = "地址id",required = true),
            @ApiImplicitParam(name = "zid",value = "周期上门id",required = true)

    })
        public Map addRecyclingOrder(@RequestParam("id")Long id
                , @RequestParam("title")String title,//废品总类型
                                     @RequestParam("ytime") String ytime,//预约时间
                                     @RequestParam("did")Long did,//地址id
                                     @RequestParam("zid")Long zid){//周期上门id
        Timestamp ytime1=null;
        if(!StringUtil.isEmpty(ytime)){
           ytime1= Timestamp.valueOf(ytime);
        }
        String randomNumber = recycleorderService.addRecyclOrder(id,title, ytime1, did, zid);

        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(randomNumber);
        return jsonResult.getDataMap();
        }
        //主页反馈星期，积分，头像
    @ApiOperation("给主页反馈星期，积分，头像")
        @PostMapping("/sendUser")
        public Map sendUser(@RequestParam("id")Long id){
            Map map = usersService.send(id);
            JsonResult jsonResult=new JsonResult();
            jsonResult.setCode("200");
            jsonResult.setData(map);
            return jsonResult.getDataMap();
        }
        //查询所有商品的
    @Autowired
    ImagesRepository imagesRepository;
    @ApiOperation("查询所有商品的接口")
    @PostMapping("/selectAllGoods")
    public Map selectAllGoods() throws BusinessException {
            List<Goods> goods = goodsorderService.selectByMongodb();
            List<Imgs> imgs = imagesRepository.findAll();
            Map map=new HashMap();
            for (Goods good : goods) {
                Long id = good.getId();
                Goods goods1 = goodsorderService.selectById(id);
                map.put("good",goods1);
                List<Imgs> imgs1 = imagesRepository.findImgsByGidEquals(id);
                map.put("imgs",imgs1);
            }
            JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    //签到
    @ApiOperation("签到接口")
    @PostMapping("/sign")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "用户id",required = true)})
    public Map sign(@RequestParam("id") Long id) throws BusinessException {
        /*Long aLong=null;
        if(id!=null&&id!=""){
            aLong = Long.valueOf(id);
        }*/
        Map map = scoreService.addSign(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    @PostMapping("/judgeState")
    @ApiOperation("签到接口续，进入签到界面，前端反我当前时间和签到状态")
    public Map getTimeAndState(@RequestParam("id")Long id) throws BusinessException {
        Map map=new HashMap();
        map.put("time", GetTimeUtil.initDateByDay().getTime()+86400000);
        Integer integer = usersService.keepState(id);
        map.put("num",integer);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    @ApiOperation("修改签到接口为未签到")
    @PostMapping("/updateState")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "用户id",required = true)})
    public Map updateState(Long id){
        usersService.updateState1(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    //任务的商品回收下面显示的那句话，要返回的是，还差多少次成为上门达人
    @ApiOperation("返回任务的商品回收下面显示的那句话和返回还差多少次成为上门达人")
    @PostMapping("/becoming")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "用户id",required = true)})
    public Map becoming(@RequestParam("id")Long id){
        Map map = usersService.haveScore(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    //商品详情页面,也作为
    @ApiOperation("商品页面详情，（好几个页面的通用接口）")
    @PostMapping("/goodsDetail")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "商品id",required = true)})
    public Map goodsDetail(@RequestParam("id") Long id) throws BusinessException {
        Goods goods = goodsService.selectById(id);
        Map map=new HashMap();
        String name = goods.getName();
        Integer count = goods.getCounts();
        Integer needPoints = goods.getNeedPoints();
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        String random = s.substring(0, 12);
        map.put("name",name);
        map.put("count",count);
        map.put("needPoints",needPoints);
        map.put("random","LXF"+random);
        map.put("remarks",goods.getRemark());
        List<Imgs> imgs = imagesRepository.findImgsByGidEquals(id);
        map.put("imgs",imgs);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }

    //积分兑换页面的提交订单接口,返回的是用户当先账户所存的积分
    @ApiOperation("积分兑换页面的提交订单接口,返回的是用户当先账户所存的积分")
    @PostMapping("/exchange")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true),
            @ApiImplicitParam(name = "points",value = "商品所花积分",required = true),
            @ApiImplicitParam(name = "gid",value = "商品id",required = true),
            @ApiImplicitParam(name = "words",value = "订单备注",required = false),
            @ApiImplicitParam(name = "address",value = "服务地址",required = true),
            @ApiImplicitParam(name = "communityId",value = "小区id",required = true)
    })
    public Map exchanggeGoods(@RequestParam("id") Long id,@RequestParam("points") Integer points,@RequestParam("gid")
                              Long gid,String words,@RequestParam("address")String address,@RequestParam("communityId")Long communityId) throws BusinessException {
        Integer exchange = goodsorderService.exchange(id, points, gid, words, address, communityId);
        JsonResult jsonResult=new JsonResult();
            jsonResult.setCode("200");
            jsonResult.setData(exchange);
            return jsonResult.getDataMap();
    }
    //积分兑换商品的时候，选择地址
    @ApiOperation("积分兑换商品的时候，选择地址")
    @PostMapping("/getAddress")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "provinces",value = "省市区",required = true)
    })
    public Map getAddress(@RequestParam("provinces")String provinces) throws BusinessException {
        List<CommunityManage> communityManages = communityManagesService.selectBy(provinces);
        List list=new ArrayList();
        for (CommunityManage communityManage : communityManages) {
            String name = communityManage.getName();
            list.add(name);
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(list);
        return jsonResult.getDataMap();
    }
    //获取当前积分
    @ApiOperation("获取当前积分接口")
    @PostMapping("/getNowPoints")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true)
    })
    public Map getNowPoints(@RequestParam("id") Long id){
        User user = usersService.selectById(id);
        Map map =new HashMap();
        map.put("nowPoints",user.getNowPoints());
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    @ApiOperation("选择小区之后，给前端返回一个小区对应的id")
    @PostMapping("/selectByNameGetCommunity")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "provinces",value = "省市区",required = true),
            @ApiImplicitParam(name = "name",value = "小区的名字",required = true)
    })
    public Map selectByNameGetCommunity(@RequestParam("provinces")String provinces,@RequestParam("name") String name) throws BusinessException {
        CommunityManage communityManage = communityManagesService.selectByNameGetCommunity(provinces,name);
        Map map=new HashMap();
        Long id = communityManage.getId();
        map.put("id",id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    @ApiOperation("给前端返回所有静态图片")
    @PostMapping("/getImg")
    public Map getImg(){
        List<GetImg> all = getImgRepository.findAll();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(all);
        return jsonResult.getDataMap();

    }












}
